package yja.gzw.app.activity

import android.widget.ScrollView
import okhttp3.*
import okio.Buffer
import yja.gzw.app.R
import yja.gzw.app.base.BaseActivity
import yja.gzw.app.databinding.ActivityLishixiangyingBinding
import yja.gzw.app.viewmodel.Mainviewmodel
import java.io.IOException


class LishixiangyingActivity :BaseActivity<Mainviewmodel, ActivityLishixiangyingBinding>(R.layout.activity_lishixiangying){
    val listre= mutableListOf<String>()

    override fun initView() {
        binding.textss.isEnabled=false

       binding.kaishi.setOnClickListener {
           main()
       }




    }

    override fun dataObservese() {

    }
    fun main() {
        val client = OkHttpClient()
        val request = Request.Builder()
            .url("https://626zonghe.32.hzgqapp.com")
            .build()

        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                println("请求失败: ${e.message}")
            }

            override fun onResponse(call: Call, response: Response) {
                response.use {
                    if (it.isSuccessful) {
                        it.body?.use { body ->
                            val source = body.source()
                            val buffer = Buffer()
                            val stringBuilder = StringBuilder()
                            try {
                                while (source.read(buffer, 1024).toInt() != -1) {
                                    val data = buffer.readUtf8()
//                                    println("读取到的数据: $data")
//                                    // 这里可以对读取到的数据进行你想要的处理，比如展示在 UI 上等
                                    stringBuilder.append(data)

                                    runOnUiThread {
                                        binding.textss.setText(stringBuilder)
                                        gonda(binding.gongdong)

                                    }


                                }
                            } catch (e: IOException) {
                                println("读取数据失败: ${e.message}")
                            }
                        }
                    } else {
                        println("请求响应失败，状态码: ${it.code}")
                    }
                }
            }
        })
        // 主线程中为了让异步请求有时间执行，这里简单等待一下，实际应用中根据情况处理
      //  Thread.sleep(5000)
    }

    fun gonda(view: ScrollView){

        view.post(Runnable { //滑动到顶部

            //滑动到底部
            view.fullScroll(ScrollView.FOCUS_DOWN)
        })


    }


}